// Copyright 2019 orivil.com. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found at https://mit-license.org.

package actions

import (
	"gitee.com/orivil/morgine/bundles/admin/image"
	"gitee.com/orivil/morgine/xx"
	"gitee.com/tugoer/psy-testing/code/container"
	"gitee.com/tugoer/psy-testing/code/models"
)

func GetSliders(c *xx.Condition) {
	doc := xx.Doc{
		Name: "获得滚动栏数据",
		Responses: xx.Responses{{
			Body: xx.MAP{"sliders": []*models.Slider{{}}},
		}},
	}
	c.Doc(doc).GET().HandleFunc("/sliders", func(ctx *xx.Context) {
		sliders, err := container.Sliders.Get()
		if err != nil {
			ctx.Error(err)
		} else {
			err = InitSliderImageUrl(sliders)
			if err != nil {
				ctx.Error(err)
			} else {
				ctx.SendJson(xx.MAP{"sliders": sliders}, false)
			}
		}
	})
}

func SaveSliders(c *xx.Condition) {
	doc := xx.Doc{
		Name: "保存滚动栏数据",
		Params: xx.Params{{
			In:     xx.Form,
			Schema: &saveSlidersParam{},
		}},
	}
	c.Doc(doc).PUT().HandleFunc("/sliders", func(ctx *xx.Context) {
		p := &saveSlidersParam{}
		if ctx.Unmarshal(p) {
			err := container.Sliders.Save(p.JsonBody)
			if err != nil {
				ctx.MsgWarning(err.Error())
			} else {
				ctx.MsgSuccess("已保存")
			}
		}
	})
}

func InitSliderImageUrl(sliders []*models.Slider) error {
	var err error
	for _, s := range sliders {
		s.ImgUrl, err = image.Storage.GetServeUrl(s.Img)
		if err != nil {
			return err
		}
	}
	return nil
}

type saveSlidersParam struct {
	JsonBody string `required:"" desc:"序列化后的 JSON 字符串"`
}
